﻿using fuzhu;
using LH.Model.ST;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using XXX.Common;
using XXX.Models;

namespace XXX.Bo
{
    class XmlOperation
    {

        /// <summary>
        /// 读取xml返回信息里的错误内容
        /// </summary>
        /// <param name="err">错误信息</param>
        /// <param name="xmlResult">return的xml内容</param>
        /// <returns></returns>
        public static string GetXmlError(string err, XDocument xmlResult)
        {
            if (err == "")
            {

                var nodezeroout = xmlResult.Descendants("zeroout").FirstOrDefault();
                if (nodezeroout != null)
                {
                    IEnumerable<XElement> xmlnodes = nodezeroout.Elements();

                    foreach (var xmlnode in xmlnodes)
                    {
                        if (xmlnode.Name.LocalName == "row")
                        {
                            string cinvcode = xmlnode.Attribute("cinvcode").Value;
                            string cbatch = xmlnode.Attribute("cbatch").Value;
                            string iquantity = xmlnode.Attribute("iquantity").Value;
                            string icurquantity = xmlnode.Attribute("icurquantity").Value;
                            err += cinvcode + "：" + cbatch + "库存不足：现存量" + icurquantity + "，出库量" + iquantity + "\r\n";

                        }
                    }
                }

                var nodetoplow = xmlResult.Descendants("toplow").FirstOrDefault();
                if (nodetoplow != null)
                {
                    IEnumerable<XElement> xmlnodes = nodetoplow.Elements();
                    foreach (var xmlnode in xmlnodes)
                    {
                        if (xmlnode.Name.LocalName == "row")
                        {
                            string cinvcode = xmlnode.Attribute("cinvcode").Value;
                            err += cinvcode + "：有最高最低库存控制；" + "\r\n";
                        }
                    }
                }
            }

            return err;
        }

        /// <summary>
        /// U8生单结果解析,badd=1代表新增
        /// </summary>
        /// <param name="cvouch">业务单据</param>
        /// <param name="badd">是否新增，=1</param>
        /// <param name="err">返回错误</param>
        /// <param name="id">生单id</param>
        /// <param name="ccode">生单单据号</param>
        /// <param name="result">返回的xml</param>
        /// <returns></returns>
        public static bool GetCoResult(string cvouch, string badd, out string err, out string id, out string ccode, string result)
        {
            var xmlResult = XDocument.Parse(result); //实例化XmlDocument
            //取return 的信息、 如果add和verify一起，有两个return，
            //20241117取最后一个的，最后一个可能是错误的
            var nodeFirst = xmlResult.Descendants("return").FirstOrDefault();
            var nodeLast = xmlResult.Descendants("return").LastOrDefault();
            //if (CanShu.U8Recordlog == "true")
            //{
            //    WriteLog write = new WriteLog();
            //    write.WriteLogs(cvouch + ":" + result);
            //}

            if (nodeFirst == null)
            {
                //特殊情况，没有return的node
                var node2 = xmlResult.Descendants("returns").LastOrDefault();
                if (node2 != null)
                {
                    var resultmes2 = node2.Attribute("sErrors0").Value;
                    string strxml = "<" + resultmes2.Substring(resultmes2.IndexOf('<') + 1);

                    xmlResult = XDocument.Parse(strxml.Trim());
                    nodeFirst = xmlResult.Descendants("return").FirstOrDefault();
                    nodeLast = xmlResult.Descendants("return").LastOrDefault();
                    //依旧获取不到return的node
                    if (nodeFirst == null)
                    {
                        err = node2.ToString();
                        id = "";
                        ccode = "";
                        return false;
                    }
                }
                else
                {
                    err = XmlOperation.GetXmlError("", xmlResult);
                    id = "";
                    ccode = "";
                    return false;
                }
            }
            //判断是否成功，用 last
            var resultcode = nodeLast.Attribute("bRet").Value;
            var resultmes = nodeLast.Attribute("sError").Value;
            if (resultcode == "False")
            {
                err = resultmes;
                err = XmlOperation.GetXmlError(err, xmlResult);
                id = "";
                ccode = "";
                return false;
            }
            else
            {
                err = "";
                if (badd == "1")
                {
                    //取单据号，用first
                    //新增的时候，取
                    id = nodeFirst.Attribute("sRetID").Value;
                    ccode = nodeFirst.Attribute("sRetCode").Value;
                }
                else
                {
                    id = "";
                    ccode = "";
                }
                return true;
            }
        }


        public static bool GetCoResult_addverify(string cvouch, string badd, out string err, out string id, out string ccode, string result)
        {
            var xmlResult = XDocument.Parse(result); //实例化XmlDocument
            //if (CanShu.U8Recordlog == "true")
            //{
            //    WriteLog write = new WriteLog();
            //    write.WriteLogs(cvouch + ":" + result);
            //}
            id = "";
            ccode = "";
            //取return 的信息、 如果add和verify一起，循环读取 
            IEnumerable<XElement> elements = xmlResult.XPathSelectElements("//return");//找根节点的直接book子节点

            string resultmes = "";
            Boolean berr = false;//是否有错误 
            foreach (XElement item in elements)
            {
                //Console.WriteLine(item.Name);
                if (item.Attribute("bRet").Value.ToLower() == "true")
                {
                    if (item.Attribute("OptType").Value == "add")
                    {
                        id = item.Attribute("sRetID").Value;
                        ccode = item.Attribute("sRetCode").Value;
                    }

                }
                else
                {
                    berr = true;
                    resultmes = item.Attribute("sError").Value;
                }

            }
            if (berr)
            {
                if (string.IsNullOrWhiteSpace(resultmes))
                {
                    //有错误明细
                    err = resultmes;
                    err = XmlOperation.GetXmlError(err, xmlResult);
                    id = "";
                    ccode = "";
                    return false;
                }
                else
                {
                    //无错误明细
                    err = resultmes;
                    id = "";
                    ccode = "";
                    return false;
                }
            }
            else
            {
                err = "";
                return true;
            }
        }



        public static RetModel GetRetModel(string result)
        {
            RetModel ret = new RetModel();
            var xmlResult = XDocument.Parse(result); //实例化XmlDocument,怎么用这个,网上去查查
            var node = xmlResult.Descendants("return");
            var resultcode = node.FirstOrDefault().Attribute("bRet").Value;
            var resultmes = node.FirstOrDefault().Attribute("sError").Value;
            if (resultcode == "False")
            {
                ret.code = 500;
                ret.message = resultmes;
            }
            else
            {
                ret.code = 200;
                if (string.IsNullOrEmpty(resultmes))
                {
                    resultmes = "ok";
                }
                ret.message = resultmes;
            }
            return ret;
        }


        public static RetModelbool GetRetModelbool (string result)
        {
            RetModelbool ret = new RetModelbool();
            var xmlResult = XDocument.Parse(result); //实例化XmlDocument,怎么用这个,网上去查查
            var node = xmlResult.Descendants("return");
            var resultcode = node.FirstOrDefault().Attribute("bRet").Value;
            var resultmes = node.FirstOrDefault().Attribute("sError").Value;
            if (resultcode == "False")
            {
                ret.code = 500;
                ret.message = resultmes;
            }
            else
            {
                ret.code = 200;
                if (string.IsNullOrEmpty(resultmes))
                {
                    resultmes = "ok";
                }
                ret.message = resultmes;
            }
            return ret;
        }
       
        
        /// <summary>
        /// 账套标记
        /// </summary>
        /// <param name="cSys"></param>
        /// <returns></returns>
        public static XDocument GetConfigXML(string cSys,string cUsername,string cUserpass)
        {
            string cServerIP = ""; 
            string cU8account = "";
            List<Orglist> objdata = Common.AppSettings.GetAppSetinglist("orglist");
            for (int i = 0; i < objdata.Count; i++)
            {
                if (objdata[i].Org == cSys)
                {
                    cServerIP = objdata[i].Server;
                    cU8account = objdata[i].U8Account;
                    break;
                }
            
            }
            
            //2、配置api的xml 登陆字符串
           

            //构建数据库连接字符串           
            string cLoginDate = DateTime.Now.ToString("yyyy-MM-dd");
            System.Xml.Linq.XDocument xconstr = new XDocument();
            //声明不要
            XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
            xconstr.Declaration = xdec;
            XElement classConfig = new XElement("configuration");
            XElement classapp = new XElement("appSettings");
            XElement classadd = new XElement("add", new XAttribute("key", "ServerIP"), new XAttribute("value", cServerIP));
            classapp.Add(classadd);
            classadd = new XElement("add", new XAttribute("key", "UserName"), new XAttribute("value", cUsername));
            classapp.Add(classadd);
            classadd = new XElement("add", new XAttribute("key", "UserPass"), new XAttribute("value", cUserpass));
            classapp.Add(classadd);
            classadd = new XElement("add", new XAttribute("key", "U8Account"), new XAttribute("value", cU8account));
            classapp.Add(classadd);
            classadd = new XElement("add", new XAttribute("key", "LoginDate"), new XAttribute("value", cLoginDate));
            classapp.Add(classadd);
            classadd = new XElement("add", new XAttribute("key", "Lic"), new XAttribute("value", cLoginDate));
            classapp.Add(classadd);
            classConfig.Add(classapp);
            xconstr.Add(classConfig);
            return xconstr;
        }

    }
}
